package com.tarena.lbs.user.service.impl;

import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.user.dao.repository.UserGroupRepository;
import com.tarena.lbs.user.pojo.param.UserGroupParam;
import com.tarena.lbs.user.pojo.po.UserGroupPO;
import com.tarena.lbs.user.pojo.query.UserGroupQuery;
import com.tarena.lbs.user.pojo.vo.UserGroupVO;
import com.tarena.lbs.user.service.UserGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserGroupServiceImpl implements UserGroupService {
    @Autowired
    private UserGroupRepository userGroupRepository;

    @Override
    public PageResult<UserGroupVO> pageList(UserGroupQuery query) {
        // 调用仓储层进行分页查询
        PageInfo<UserGroupPO> pageInfo = userGroupRepository.pageList(query);

        // 构造返回结果
        PageResult<UserGroupVO> result = new PageResult<>();
        result.setPageNo(pageInfo.getPageNum());
        result.setPageSize(pageInfo.getPageSize());
        result.setTotal(pageInfo.getTotal());

        // 转换PO到VO
        List<UserGroupPO> pos = pageInfo.getList();
        if (pos != null && !pos.isEmpty()) {
            List<UserGroupVO> vos = pos.stream().map(po -> {
                UserGroupVO vo = new UserGroupVO();
                BeanUtils.copyProperties(po, vo);
                return vo;
            }).collect(Collectors.toList());
            result.setObjects(vos);
        }

        return result;
    }

    @Override
    public void save(UserGroupParam param) throws BusinessException {
        // 参数校验
        Asserts.isTrue(param.getGroupName() == null || param.getGroupName().isEmpty(),
                new BusinessException("-2", "人群名称不能为空"));
        Asserts.isTrue(param.getUserNumber() == null,
                new BusinessException("-2", "预估人数不能为空"));

        // 组装UserGroupPO对象
        UserGroupPO userGroupPO = new UserGroupPO();
        BeanUtils.copyProperties(param, userGroupPO);
        userGroupPO.setCreateAt(new Date());
        // 设置商家ID，实际项目中应该从上下文中获取当前登录商家ID
        userGroupPO.setBusinessId(1);

        // 保存到数据库
        userGroupRepository.save(userGroupPO);
    }


}
